<?php
require_once OVF_FS_WEB_ROOT.'/app/_inc/class.ovfDocGen.php';

class wfmPagina {
	public $idPagina = 0;
	public $codPagina = "";
	public $idModulo = 0;
	public $codModulo = "";
	public $oMod = null;
	public $regolaInp = "";
	public $regolaVal = "";
	public $regolaOut = "";
	public $aDatiDB;
	public $aDatiInp;
	public $errno = 0;
	public $error = '';
	
	public function __construct(&$oMod, $id,$tipoId='pag') {
		global $objDB, $objSess;
		if ($tipoId=='ini' || $tipoId=='vis') {
			$id = intval($oMod->aRec['id_pagina_'.$tipoId]);
		}
		$sql_sel = "SELECT p.* "
				.", rinp.cod_regola AS regola_inp, rval.cod_regola AS regola_val, rout.cod_regola AS regola_out" 
				." FROM wfm_pagine p " 
				." LEFT JOIN wfm_regole rinp ON rinp.id_regola = p.id_regola_inp "
				." LEFT JOIN wfm_regole rval ON rinp.id_regola = p.id_regola_val "
				." LEFT JOIN wfm_regole rout ON rinp.id_regola = p.id_regola_out "
				." WHERE p.id_pagina = $id";
		$objDB->query($sql_sel,'selPagina');
		$aRecP = $objDB->fetch('selPagina');
		if (!$aRecP || $aRecP['id_modulo'] != $oMod->idModulo) {
			return false;
		}
		$this->idPagina = $aRecP['id_pagina'];
		$this->codPagina = $aRecP['cod_pagina'];
		$this->tipoInst = $aRecP['tipo_inst'];
		$this->codPagina = $aRecP['cod_pagina'];
		$this->oMod = $oMod;
		$this->codModulo = $this->oMod->codModulo;
		$this->idModulo = $this->oMod->idModulo;
		$this->regolaInp = "reginp_".$aRecP['regola_inp'];
		$this->regolaVal = "regval_".$aRecP['regola_val'];
		$this->regolaOut = "regout_".$aRecP['regola_out'];
	}
	
	private function setErr($err=0,$des='') {
		$this->errno = $err;
		$this->error = $des;
		return ($err==0);
	}
	
	public function prepIns() {
		global $objDB, $objSess;
		$this->aDatiDB = array();
		$this->aDatiDB["A_id_rec"] = 0;
		//$this->aDatiDB["A_id_modulo"] = $this->idModulo;
		$this->aDatiDB["A_id_utente_ins"] = $objSess->idUtente;
		$this->aDatiDB["A_id_utente_mod"] = $objSess->idUtente;
		$this->aDatiDB["A_id_utente_can"] = 0;
		$this->aDatiDB["A_data_ora_ins"] = date("Y-m-d H:i:s");
		$this->aDatiDB["A_data_ora_mod"] = date("Y-m-d H:i:s");
		$this->aDatiDB["A_data_ora_can"] = '0000-00-00 00:00:00';
		foreach($this->oMod->aCampi as $sNomX => $aCX) {
			$this->aDatiDB["A_".$sNomX] = $aCX['def'];
		}
		$this->DB2Inp();
	}
	
	public function prepMod(&$aRec) {
		global $objDB, $objSess;
		$this->aDatiDB = array();
		foreach($aRec as $sNomX => $valX) {
			$this->aDatiDB["A_".$sNomX] = $valX;
		}
		$this->DB2Inp();
	}
	
	public function getHtmlComandi() {
		global $objDB, $objSess;
		$sql_sel = "SELECT c.*, racm.cod_regola AS regola_acm" 
				." FROM wfm_comandi c " 
				." LEFT JOIN wfm_regole racm ON racm.id_regola = c.id_regola_acm "
				." WHERE c.id_pagina = ".$this->idPagina
				." ORDER BY c.cod_comando ";
		$objDB->query($sql_sel,'selPagina');
		$sCmd = "";
		while($aRecC = $objDB->fetch('selPagina')){
			if (!empty($aRecC['regola_acm'])) {
				$sRet = $this->eseguiRegola("regacm_".$aRecC['regola_acm']);
				if (!$sRet) {
					continue;
				}
			}
			$sCmd .="&nbsp;&nbsp;&nbsp;";
			$sCmd .= "<a href=\"javascript:submCmd('".$aRecC['id_comando']."','".$aRecC['cod_comando']."');\" "
				." class=\"cmd1\">".$aRecC['descr']."</a>\n";
		}
		return $sCmd;
	}
	
	public function getComando($idComando) {
		global $objDB, $objSess;
		$sql_sel = "SELECT c.*, racm.cod_regola AS regola_acm" 
				." FROM wfm_comandi c " 
				." LEFT JOIN wfm_regole racm ON racm.id_regola = c.id_regola_acm "
				." WHERE c.id_comando = ".$idComando;
		$objDB->query($sql_sel,'selPagina');
		$aRecC = $objDB->fetch('selPagina');
		return $aRecC;
	}
	
	public function getHtmlPagina($modalita='vis') {
		global $objDB, $objSess;
		if ($this->tipoInst == 'pers') {
			$pagName = "pagina_".$this->codPagina;
			$pagPath = OVF_FS_WEB_ROOT."/pers/wfma/".$this->codModulo."/$pagName.php";
			if (file_exists($pagPath)) {
				return "@@include=".$pagPath;
			}
		}
		$sH1 = "<table cellpadding='3' cellspacing='1' width='100%'>\n";
		$sH2 = $this->oMod->getHtmlCampiStd($modalita);
		$sH3 = "</table>\n";
		return $sH1.$sH2.$sH3;
	}
	
	public function eseguiIns() {
		global $objDB, $objSess;
		$msg = "";
		foreach($_REQUEST as $nX => $vX) {
			$this->aDatiInp[$nX] = reqVar($nX);
		}
		foreach($this->oMod->aCampi as $sNomX => $aCX) {
			switch($aCX['tip']) {
				case 'data':
					if (trim($this->aDatiInp["A_".$sNomX]) != ""
					&& str2date($this->aDatiInp["A_".$sNomX]) === false) {
						$msg .= "campo '".$aCX['lab']."' - data errata<br>";
					}
					break;
				case 'numero':
				case 'intero':
					if (trim($this->aDatiInp["A_".$sNomX]) != ""
					&& str2num($this->aDatiInp["A_".$sNomX]) === false) {
						$msg .= "campo '".$aCX['lab']."' - numero errato<br>";
					}
					break;
				default:
					break;
			}
		}		
		$msg .= $this->eseguiRegola($this->regolaVal,reqvar("X_comando"));
		if ($msg != "") {
			return $msg;
		}
		$this->inp2DB();
		$aCmd = $this->getComando(reqvar("X_id_comando"));
		$this->aDatiDB['A_id_utente_ins'] = $objSess->idUtente;
		$this->aDatiDB['A_dataora_ins'] = date('Y-m-d H:i:s');
		$this->aDatiDB['A_id_utente_mod'] = $objSess->idUtente;
		$this->aDatiDB['A_dataora_mod'] = date('Y-m-d H:i:s');
		if ($aCmd['stato_fin']!=0) {
			$this->aDatiDB['A_stato'] = $aCmd['stato_fin'];
		}
		if ($aCmd['id_pagina_fin']!=-1) {
			$this->aDatiDB['A_id_pagina'] = $aCmd['id_pagina_fin'];
		}
		if (!empty($aCmd['regola_stf'])) {
			$this->eseguiRegola($aCmd['regola_stf'],reqvar("X_comando"));
		}
		$this->eseguiRegola($this->regolaOut);
		if (!empty($aCmd['regola_not'])) {
			$this->eseguiRegola($aCmd['regola_not'],reqvar("X_comando"));
		}
		$sSql = "INSERT INTO wfm_rec_".$this->codModulo." SET stato = ".intval($this->aDatiDB['A_stato']); 
		foreach($this->oMod->aFields as $sField => $aFX) {
			if ($sField == 'id_rec' || $sField == 'stato' 
			|| !isset($this->aDatiDB['A_'.$sField])) {
				continue;
			}
			$sSql .= ",$sField = '".addslashes($this->aDatiDB['A_'.$sField])."'";
		}
		$objDB->exec($sSql);
		dbg_("eseguiIns:".$sSql);
		header("location: recList.php?id=".$this->idModulo."&xsn=".XSN);
		exit;
	}
	
	public function eseguiMod() {
		global $objDB, $objSess;
		$msg = "";
		foreach($_REQUEST as $nX => $vX) {
			$this->aDatiInp[$nX] = reqVar($nX);
		}
		foreach($this->oMod->aCampi as $sNomX => $aCX) {
			switch($aCX['tip']) {
				case 'data':
					if (trim($this->aDatiInp["A_".$sNomX]) != ""
					&& str2date($this->aDatiInp["A_".$sNomX]) === false) {
						$msg .= "campo '".$aCX['lab']."' - data errata<br>";
					}
					break;
				case 'numero':
				case 'intero':
					if (trim($this->aDatiInp["A_".$sNomX]) != ""
					&& str2num($this->aDatiInp["A_".$sNomX]) === false) {
						$msg .= "campo '".$aCX['lab']."' - numero errato<br>";
					}
					break;
				default:
					break;
			}
		}		
		$msg .= $this->eseguiRegola($this->regolaVal,reqvar("X_comando"));
		if ($msg != "") {
			return $msg;
		}
		$this->inp2DB();
		$aCmd = $this->getComando(reqvar("X_id_comando"));
		$this->aDatiDB['A_id_utente_mod'] = $objSess->idUtente;
		$this->aDatiDB['A_dataora_mod'] = date('Y-m-d H:i:s');
		if ($aCmd['stato_fin']!=0) {
			$this->aDatiDB['A_stato'] = $aCmd['stato_fin'];
		}
		if ($aCmd['id_pagina_fin']!=-1) {
			$this->aDatiDB['A_id_pagina'] = $aCmd['id_pagina_fin'];
		}
		if (!empty($aCmd['regola_stf'])) {
			$this->eseguiRegola($aCmd['regola_stf'],reqvar("X_comando"));
		}
		$this->eseguiRegola($this->regolaOut);
		if (!empty($aCmd['regola_not'])) {
			$this->eseguiRegola($aCmd['regola_not'],reqvar("X_comando"));
		}
		$msg = $this->scriviLog();
		if ($msg != "") {
			return $msg;
		}
		$sSql = "UPDATE wfm_rec_".$this->codModulo;
		$sep = " SET ";
		foreach($this->oMod->aFields as $sField => $aFX) {
			if ($sField == 'id_rec' || $sField == 'id_modulo' 
			|| !isset($this->aDatiDB['A_'.$sField])) {
				continue;
			}
			$sSql .= $sep."$sField = '".addslashes($this->aDatiDB['A_'.$sField])."'";
			$sep = ", ";
		}
		$sSql .= " WHERE id_rec = ".reqVar('idr');
		$objDB->exec($sSql);
		dbg_("eseguiMod:".$sSql);
		header("location: recList.php?id=".$this->idModulo."&xsn=".XSN);
		exit;
	}
	
	private function scriviLog() {
		global $objDB, $objSess;
		$sSql = "SELECT * FROM wfm_rec_".$this->codModulo
			." WHERE id_rec = ".reqVar('idr');
		$objDB->exec($sSql);
		if (!$aOld = $objDB->fetch()) return "log non registrato !!!";
		$bDiff = false;
		foreach($this->oMod->aFields as $sField => $aFX) {
			if ($sField == 'data_ora_agg' 
			|| $sField == 'id_utente_agg' 
			|| !isset($this->aDatiDB['A_'.$sField])) {
				continue;
			}
			if ($aOld[$sField] == $this->aDatiDB['A_'.$sField]) {
				continue;
			}
			$bDiff = true;
		}
		if (!$bDiff) return "";
		$sep = "SET ";
		$sSql = "INSERT INTO wfm_rec_".$this->codModulo."_log ";
		foreach($this->oMod->aFields as $sField => $aFX) {
			$sSql .= $sep.$sField." = '".addslashes($aOld[$sField])."' ";
			$sep = ", ";
		}
		$objDB->exec($sSql);
		return "";	
	}
	
	public function DB2Inp() {
		foreach($_REQUEST as $nX => $vX) {
			$this->aDatiInp[$nX] = reqVar($nX);
		}
		foreach($this->aDatiDB as $sANomX => $valX) {
			if (isset($_REQUEST[$sANomX])) {
				continue;
			}
			$sNomX = substr($sANomX,2);
			if (isset($this->oMod->aCampi[$sNomX])) {
				switch($this->oMod->aCampi[$sNomX]['tip']) {
					case 'data':
						$this->aDatiInp[$sANomX] = YMD2DMY($this->aDatiDB[$sANomX]);
						break;
					case 'numero':
						$this->aDatiInp[$sANomX] = num2str($this->aDatiDB[$sANomX],$this->oMod->aCampi[$sNomX]['dec']);
						break;
					case 'intero':
						$this->aDatiInp[$sANomX] = num2str($this->aDatiDB[$sANomX],0);
						break;
					case 'si/no':
						$this->aDatiInp[$sANomX] = ($this->aDatiDB[$sANomX]=='S')?'S':'N';
						break;
					default:
						$this->aDatiInp[$sANomX] = $this->aDatiDB[$sANomX];
						break;
				}
			} else {
				$this->aDatiInp[$sANomX] = $this->aDatiDB[$sANomX];
			}
		}
		$this->eseguiRegola($this->regolaInp);
		foreach($this->aDatiInp as $sANomX => $aCX) {
			if (!isset($_REQUEST[$sANomX])) {
				$_REQUEST[$sANomX] = $this->aDatiInp[$sANomX];
				continue;
			}
		}
		return '';
	}
	
	public function inp2DB() {
		foreach($this->oMod->aCampi as $sNomX => $aCX) {
			switch($aCX['tip']) {
				case 'data':
					$this->aDatiDB["A_".$sNomX] = DMY2YMD($this->aDatiInp["A_".$sNomX]);
					break;
				case 'numero':
				case 'intero':
					$this->aDatiDB["A_".$sNomX] = str2num($this->aDatiInp["A_".$sNomX]);
					break;
				case 'si/no':
					$this->aDatiDB["A_".$sNomX] = ($this->aDatiInp["A_".$sNomX]=='S')?'S':'N';
					break;
				default:
					$this->aDatiDB["A_".$sNomX] = $this->aDatiInp["A_".$sNomX];
					break;
			}
		}
		$this->eseguiRegola($this->regolaOut);
		return '';
	}
	
	
	private function eseguiRegola($regola,$comando='') {
		if (strlen($regola)<8) {
			return '';
		}
		$regolaPath = OVF_FS_WEB_ROOT."/pers/wfma/".$this->codModulo."/$regola.php";
		//dbg_("regolaPath=$regolaPath");
		$sRet = '';
		if (file_exists($regolaPath)) {
			$script = file_get_contents($regolaPath);
			$posFun = strpos($script,'function ');
			$posPar = strpos($script,'{',$posFun);
			if ($posFun !== false && $posPar !== false) {
				$nomeFunz = uniqid($regola);
				$script = "function $nomeFunz(&\$aDatiInp,&\$aDatiDB,\$comando='')".substr($script,$posPar);
				eval($script);
				$sRet .= $nomeFunz($this->aDatiInp,$this->aDatiDB,$comando);
			}
		}
		return $sRet;
	}
	
} //fine classe